package com.letao.service.impl;

import com.letao.common.pojo.PictureResult;
import com.letao.common.utils.FtpUtil;
import com.letao.common.utils.IDUtils;
import com.letao.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by ac on 2017/1/10.
 */
@Service
public class PictureServiceImpl implements PictureService {

    @Value("${FILE_HOST}")
    private String FILE_HOST;

    @Value("${FILE_PORT}")
    private Integer FILE_PORT;

    @Value("${FILE_USERNAME}")
    private String FILE_USERNAME;

    @Value("${FILE_PASSWORD}")
    private String FILE_PASSWORD;

    @Value("${FILE_BASE_PAHT}")
    private String FILE_BASE_PAHT;

    @Override
    public PictureResult uploadFile(MultipartFile multipartFile) {
        String result = this.saveFile(multipartFile);
        return result == null ? new PictureResult(1, "上传失败", null) : new PictureResult(0, null,"http://"+ FILE_HOST + result);
    }

    private String saveFile(MultipartFile multipartFile){
        if(multipartFile == null && multipartFile.isEmpty()){
            return null;
        }
        //以日期生成文件路径
        StringBuffer filePath = new StringBuffer();
        filePath.append("/");
        filePath.append(new SimpleDateFormat("yyyy").format(new Date()));
        filePath.append("/");
        filePath.append(new SimpleDateFormat("MM").format(new Date()));
        filePath.append("/");
        filePath.append(new SimpleDateFormat("dd").format(new Date()));

        String originalFilename = multipartFile.getOriginalFilename();
        String fileName = IDUtils.genImageName() + originalFilename.substring(originalFilename.indexOf("."));
        String finishFilePath = filePath.toString() + "/" + fileName;
        boolean result = false;
        try {
            result = FtpUtil.uploadFile(FILE_HOST, FILE_PORT.intValue(), FILE_USERNAME, FILE_PASSWORD, FILE_BASE_PAHT, filePath.toString(), fileName , multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result ? finishFilePath : null;
    }
}
